package com.iot.modbus.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TaskManager {

    private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(128);
    private static final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();

    /**
     *提交任务
     */
    public static synchronized void submit(final String key,Runnable command, long delay) {
        ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(command, 10, delay, TimeUnit.MICROSECONDS);
        futureMap.put(key, scheduledFuture);
    }

    /**
     * 取消任务
     */
    public static synchronized void cancel(final String key) {
        futureMap.get(key).cancel(true);
        futureMap.remove(key);
    }

    /**
     * 修改任务
     */
    public static synchronized void edit(final String key,Runnable command, long delay) {
        cancel(key);
        submit(key, command, delay);
    }


}
